package com.ja.openchat.ui.me;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.ja.openchat.views.SetPwdDialog;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.setting.AccountTtlInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.Common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.blankj.utilcode.util.StringUtils.getString;

public class AccountSecurityActivity extends JaBaseActivity {
    @BindView(R.id.accountTtlText)
    TextView accountTtlText;
    @BindView(R.id.modifyPassword)
    TextView modifyPassword;
    @BindView(R.id.currentMobileText)
    TextView currentMobileText;
    @BindView(R.id.findByPhoneNumberSwitch)
    Switch findByPhoneNumberSwitch;
    public static final int[] chooseValues = {30,90,180,365};
    public List<String> chooseLables = new ArrayList<>();
    private boolean hasPassword;
    @Override
    public void initData() {
        setTitle(getString(R.string.safety_text));
        findViewById(R.id.toolbar).setBackgroundResource(R.color.color_12172a);
        ImageView ivBack = findViewById(R.id.iv_bar_back);
        ivBack.setImageResource(R.drawable.back_white);
        TextView titleText = findViewById(R.id.tv_bar_title);
        titleText.setTextColor(getResources().getColor(R.color.white));

        chooseLables.add(getString(R.string.a_month_text));
        chooseLables.add(getString(R.string.three_months));
        chooseLables.add(getString(R.string.six_months));
        chooseLables.add(getString(R.string.one_year));

        UserInfo user = UserInfo.getUserInfo();
        currentMobileText.setText(user!=null?Common.formatPhoneNumber(user.phone_number):"");
        findByPhoneNumberSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editMultiOnline(findByPhoneNumberSwitch.isChecked());
            }
        });
        load();
        requestInfoData();
//        setDunAnim();
    }
    private void load(){
        loadAccountTtl();
        loadMultiOnline();
    }

    private void loadMultiOnline(){
        TelegramManager.getTelegramManager().getMultiOnline(this, new TgResultBlock<Boolean>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, Boolean obj) {
                findByPhoneNumberSwitch.setChecked(obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private int accountTtlIndex = 0;
    private void loadAccountTtl(){
        TelegramManager.getTelegramManager().getAccountTtl(this, new TgResultBlock<AccountTtlInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, AccountTtlInfo obj) {
                if(obj!=null){
                    int value = obj.days;
                    for(int i =0;i<chooseValues.length;i++){
                        if(value<=chooseValues[i]){
                            accountTtlIndex = i;
                            break;
                        }
                    }
                }
                accountTtlText.setText(chooseLables.get(accountTtlIndex));
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });

    }


    @OnClick({R.id.deleteAccountBtn,R.id.logoutDeviceBtn,R.id.offlineAccountBtn,R.id.alterMobileBtn,R.id.modifyPassword})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.deleteAccountBtn:
                startActivity(new Intent(this,LogoutDeviceActivity.class));
                break;
            case R.id.logoutDeviceBtn:
                startActivity(new Intent(this,LoginDevicesActivity.class));
                break;
            case R.id.offlineAccountBtn:
                ChooseListDialog.showChooseListDialog(this, chooseLables, accountTtlIndex, new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        editAccountTtl(chooseValues[position]);
                    }
                });
                break;
            case R.id.alterMobileBtn:

                break;
            case R.id.modifyPassword:
                //修改密码
//                Bundle bundle = new Bundle();
//                bundle.putBoolean("hasPassword", hasPassword);
//                startContainerActivity(SetPwdFragment.class.getCanonicalName(), bundle);
                SetPwdDialog dialog = new SetPwdDialog(this, hasPassword, new SetPwdDialog.OnButtonClickListener() {
                    @Override
                    public void onClick(String oldPassword, String newPassword,SetPwdDialog pwdDialog) {
                        requestPasswordData(oldPassword,newPassword, pwdDialog);
                    }
                });
                new XPopup.Builder(this)
                        .autoOpenSoftInput(false)
                        .moveUpToKeyboard(false)
                        .isViewMode(true)
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(dialog).show();
                break;
        }
    }

    private void editMultiOnline(boolean isMultiOnline){
        showProgress();
        TelegramManager.getTelegramManager().toggleMultiOnline(this, isMultiOnline, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&obj.ok){
                    loadMultiOnline();
                    if(!isMultiOnline){
                        TelegramManager.getTelegramManager().terminateAllOtherSessions(AccountSecurityActivity.this, new TgResultBlock<TgResponse>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {

                            }
                        });
                    }
                }else{
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void editAccountTtl(int days){
        showProgress();
        TelegramManager.getTelegramManager().setAccountTtl(this, new AccountTtlInfo(days), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&obj.ok){
                    loadAccountTtl();
                }else{
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_account_security;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void setStatusBar() {
        super.setStatusBar();
        ImmersionBar.with(this)
                .navigationBarColor("#ffffff")
                .statusBarDarkFont(true)
                .statusBarColor("#12172a").init();
    }

    private AnimatorSet animatorSet;
    private void setDunAnim(){
        ImageView image = findViewById(R.id.image);
        //生成一个透明度变化的属性动画对象
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(image, "alpha", 1, 0.3f, 0.2f, 0);
        alphaAnimator.setRepeatCount(1000);
        //XY方向都放大3倍
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(image, "scaleX", 1f, 1.3f);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(image, "scaleY", 1f, 1.3f);
        scaleXAnimator.setRepeatCount(1000);
        scaleYAnimator.setRepeatCount(1000);

        //生成一个animatorSet对象
        animatorSet = new AnimatorSet();
        animatorSet.setDuration(3000);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        //播放多条动画
        animatorSet.playTogether(alphaAnimator, scaleXAnimator, scaleYAnimator);

        animatorSet.start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(animatorSet != null){
            animatorSet.cancel();
        }
    }

    public void requestInfoData() {
        TelegramManager.getTelegramManager().queryUserMyInfo(getApplication(), new TgResultBlock<UserMyInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserMyInfo obj) {
                if (obj != null) {
                    hasPassword = obj.hasPassword;
//                    pwdDes.set(obj.hasPassword ? "修改密码" : "设置密码");
                    if(hasPassword){
                        modifyPassword.setText(getResources().getString(R.string.modify_login_password_text));
                    }else {
                        modifyPassword.setText(getResources().getString(R.string.set_login_password_text));
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }


    public void requestPasswordData(String oldPassword,String newPassword,SetPwdDialog dialog) {
        showProgress();
        TelegramManager.getTelegramManager().alterLoginPassword(getApplication()
                , hasPassword ? oldPassword : null
                , newPassword, new TgResultBlock<TgResponse>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        hideProgress();
                        if (obj.ok) {
                            Bundle bundle = new Bundle();
                            bundle.putString("success", getString(R.string.set_new_pwd_success));
                            startContainerActivity(SetPwdSuccessFragment.class.getCanonicalName(), bundle);
                            dialog.dismiss();
                        }else {
                            showWarnTip(obj.errString);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                });
    }
}
